package cn.felord.common.controller;


import cn.felord.common.bean.Rest;
import cn.felord.common.bean.RestBody;
import cn.felord.common.entity.SysRole;
import cn.felord.common.service.ISysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.Property;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Set;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author dax
 * @since 2018 -09-13
 */
@RestController
@RequestMapping("/role")
public class SysRoleController {
    @Resource
    private ISysRoleService iSysRoleService;

    /**
     * Gets user info.
     *
     * @param userId the user id
     * @return the user info
     */
    @PostMapping("/user/{userId}")
    public Rest getUserInfo(@PathVariable String userId) {
        Set<String> roles = iSysRoleService.selectUserRoleByUserId(userId);
        return RestBody.okData(roles);
    }

    /**
     * Role list rest.
     *
     * @param current the current
     * @param size    the size
     * @return the rest
     */
    @GetMapping("/list")
    public Rest roleList(long current, long size) {
        Page<SysRole> sysRolePage = new Page<>(current, size);
        return RestBody.okData(iSysRoleService.selectList(sysRolePage));
    }

    @PostMapping("/add")
    public Rest addRole(SysRole sysRole) {
        sysRole.setCreateTime(LocalDateTime.now());
        Integer integer = iSysRoleService.saveRole(sysRole);
        if (integer > 0) {
            return RestBody.ok("添加角色成功");
        }
        return RestBody.failure("添加角色失败");
    }

    /**
     * 检查角色名是否重复.
     *
     * @param roleName the role name
     * @return the rest
     */
    @GetMapping("/checkName")
    public Rest checkRoleName(@RequestParam String roleName) {
        if (check(SysRole::getRoleName, roleName) > 0) {
            return RestBody.failure("角色名不能重复");
        }
        return RestBody.ok();
    }

    /**
     * 检查角色代码是否重复.
     *
     * @param roleDesc the role desc
     * @return the rest
     */
    @GetMapping("/checkDesc")
    public Rest checkRoleDesc(@RequestParam String roleDesc) {
        if (check(SysRole::getRoleDesc, roleDesc) > 0) {
            return RestBody.failure("角色代码不能重复");
        }
        return RestBody.ok();
    }

    private Integer check(Property<SysRole, ?> property, Object val) {
        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
        sysRoleQueryWrapper.lambda().eq(property, val).eq(SysRole::getState, '1');
        return iSysRoleService.count(sysRoleQueryWrapper);
    }
}
